package juc;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者-消费者模型（Demo）
 * 生产者-生产10个对象供消费者消费，消费者消费完再生产10个对象，生产者生产完再消费，消费者消费完再退出。
 * 使用Lock 锁的方式的方式完成
 */
public class ProducerConsumerLock {

    // 生产对象的最大数量
    private static final int MAX_ITEMS = 200;

    // 缓冲队列大小
    private final int MAX_CAPACITY = 10;

    private final Queue<Integer> queue = new LinkedList<>();
    private final Lock lock = new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();
    private boolean shouldStop = false;

    public class Producer implements Runnable {
        @Override
        public void run() {
            int producedCount = 0;
            while (producedCount < MAX_ITEMS) { // 假设总共生产20个对象
                lock.lock();
                try {
                    while (queue.size() == MAX_CAPACITY) {
                        notFull.await();
                    }
                    int product = producedCount + 1;
                    queue.add(product);
                    Thread.sleep(2000);
                    System.out.println("Produced: " + product);
                    producedCount++;
                    if (producedCount % MAX_CAPACITY == 0) {
                        System.out.println("Producer produced 10 items, waiting for consumer to finish.");
                    }
                    notEmpty.signalAll();
                    if (producedCount >= MAX_ITEMS) {
                        shouldStop = true;
                        notEmpty.signalAll();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public class Consumer implements Runnable {
        @Override
        public void run() {
            int consumedCount = 0;
            while (true) {
                lock.lock();
                try {
                    while (queue.isEmpty() && !shouldStop) {
                        notEmpty.await();
                    }
                    if (shouldStop && queue.isEmpty()) {
                        break;
                    }
                    int product = queue.poll();
                    System.out.println("Consumed: " + product);
                    consumedCount++;
                    if (consumedCount % MAX_CAPACITY == 0) {
                        System.out.println("Consumer consumed 10 items, waiting for producer to produce.");
                    }
                    notFull.signalAll();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumerLock pc = new ProducerConsumerLock();
        Thread producerThread = new Thread(pc.new Producer());
        Thread consumerThread = new Thread(pc.new Consumer());

        producerThread.start();
        consumerThread.start();
    }

}
